package com.sharemarking.wa.platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.entity.*;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.platform.dto.orgVerify.OrgVerifyDto;
import com.sharemarking.wa.platform.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author dxy
 */
@Service
public class OrgVerifyService {
    @Autowired
    private OrgVerifyMapper orgVerifyMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrgVerifyAttachmentMapper orgVerifyAttachmentMapper;
    @Autowired
    private WasteTypeMapper wasteTypeMapper;
    @Autowired
    private OrgWasteTypeMapper orgWasteTypeMapper;

    /**
     * 获取我的企业认证信息
     *
     * @return
     * @throws Exception
     */
    public ResponseParams<?> getInfo() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        Integer role = memberMapper.getRoleByMemberId(memberId);
        QueryWrapper<OrgVerify> queryOne = new QueryWrapper<>();
        queryOne.eq("member_id", memberId);
        OrgVerify orgVerify = orgVerifyMapper.selectOne(queryOne);

        OrgVerifyDto orgVerifyDto = new OrgVerifyDto();
        if (orgVerify != null) {
            BeanUtils.copyProperties(orgVerify, orgVerifyDto);
        }

        OrgVerifyAttachment orgVerifyAttachment = orgVerifyAttachmentMapper.selectOne(new QueryWrapper<OrgVerifyAttachment>().eq("org_verify_id",orgVerify.getId()).eq("type",1));
        if (!ObjectUtils.isEmpty(orgVerifyAttachment))
            orgVerifyDto.setLicenseUrl(orgVerifyAttachment.getAttachment());

        orgVerifyAttachment = orgVerifyAttachmentMapper.selectOne(new QueryWrapper<OrgVerifyAttachment>().eq("org_verify_id",orgVerify.getId()).eq("type",2));
        if (!ObjectUtils.isEmpty(orgVerifyAttachment))
            orgVerifyDto.setDangerousUrl(orgVerifyAttachment.getAttachment());

        if (role == 1) {
            orgVerifyDto.setWasteTypeList(orgVerifyMapper.getOrgWasteTypeList(orgVerify.getOrgId()));
        } else {
            List<String> attachments =  orgVerifyAttachmentMapper.getAttachment(orgVerify.getId());
            List<String> attachmentList = new ArrayList<>();
            for (String a:attachments) {
                a = a.replace("wasteList/","");
                attachmentList.add(a);
            }
            orgVerifyDto.setAttachmentList(attachmentList);
        }
        return ResponseParams.ok(orgVerifyDto);
    }

    /**
     * 新增或提交我的企业认证
     *
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> addOrEdit() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String name = request.getParameter("name");
        String industry = request.getParameter("industry");
        String legalRepresentative = request.getParameter("legalRepresentative");
        String address = request.getParameter("address");
        String licenseNumber = request.getParameter("licenseNumber");
        String wasteScale = request.getParameter("wasteScale");
        String attachmentList = request.getParameter("attachmentList");
        String licenseLink = request.getParameter("licenseLink");
        String wasteTypeList = request.getParameter("wasteTypeList");
        String addressId = request.getParameter("addressId");
        //判断角色
        Integer role = memberMapper.getRoleByMemberId(memberId);
        if (!role.equals(0) && !role.equals(1)) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }

        if (role.equals(0)) {
            if (StringUtils.isEmpty(wasteScale)) {
                throw RequestException.create(ResponseParams.requiredParamsIsMissing("wasteScale"));
            }
            if (StringUtils.isEmpty(attachmentList)) {
                throw RequestException.create(ResponseParams.requiredParamsIsMissing("attachmentList"));
            }
            licenseLink = null;
            wasteTypeList = null;
        } else if (role.equals(1)) {
            if (StringUtils.isEmpty(licenseLink)) {
                throw RequestException.create(ResponseParams.requiredParamsIsMissing("licenseLink"));
            }
            if (StringUtils.isEmpty(wasteTypeList)) {
                throw RequestException.create(ResponseParams.requiredParamsIsMissing("wasteTypeList"));
            }
            wasteScale = null;
        }

        if (StringUtils.isEmpty(name)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("name"));
        }
        if (StringUtils.isEmpty(industry)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("industry"));
        }
        if (StringUtils.isEmpty(legalRepresentative)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("legalRepresentative"));
        }
        if (StringUtils.isEmpty(address)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("address"));
        }
        if (StringUtils.isEmpty(licenseNumber)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("licenseNumber"));
        }


        QueryWrapper<OrgVerify> queryOne = new QueryWrapper<>();
        queryOne.eq("member_id", memberId);
        OrgVerify orgVerify = orgVerifyMapper.selectOne(queryOne);

//        if (orgVerify != null && orgVerify.getExamState() == 1) {
//            throw RequestException.create(ResponseParams.isDataError("企业认证成功，请勿重复提交"));
//        }

        if (orgVerify == null) {
            orgVerify = new OrgVerify();
        }

        orgVerify.setMemberId(memberId);
        orgVerify.setName(name);
        orgVerify.setIndustry(industry);
        orgVerify.setLegalRepresentative(legalRepresentative);
        orgVerify.setAddress(address);
        orgVerify.setLicenseNumber(licenseNumber);
        orgVerify.setExamState(0);
        orgVerify.setWasteScale(wasteScale);
        orgVerify.setLicenseLink(licenseLink);

        //校验证件json格式是否正确
        List<OrgVerifyAttachment> orgVerifyAttachmentList;
        try {
            orgVerifyAttachmentList = JSON.parseArray(attachmentList, OrgVerifyAttachment.class);
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.isDataError("attachmentList JSON格式错误"));
        }

        if (StringUtils.isEmpty(orgVerify.getId())) {
            orgVerify.setCreateDate(new Date());
            //冗余orgId
            QueryWrapper<Org> orgQueryWrapper = new QueryWrapper<>();
            orgQueryWrapper.eq("member_id", memberId);
            Org org = orgMapper.selectOne(orgQueryWrapper);
            orgVerify.setOrgId(org.getId());
            //插入数据
            orgVerifyMapper.insert(orgVerify);

        } else {
            //更新数据
            orgVerify.setUpdateDate(new Date());
            //将member表中的real_name 去除冗余
            memberMapper.updateRealNameNull(memberId);
            //将org表中的real_name 去除冗余
            orgMapper.updateRealNameNull(memberId);
            //更新
            orgVerifyMapper.updateById(orgVerify);

            orgVerifyAttachmentMapper.delete(new QueryWrapper<OrgVerifyAttachment>().eq("org_verify_id", orgVerify.getId()));
            if (role.equals(1)) {
                orgWasteTypeMapper.delete(new QueryWrapper<OrgWasteType>().eq("org_verify_id", orgVerify.getId()));
            }
        }

        if (role.equals(0)) {
            //产废端，将危废清单写入表中
            for (OrgVerifyAttachment orgVerifyAttachment : orgVerifyAttachmentList) {
                if (orgVerifyAttachment.getType().equals(0)) {
                    String attachmentLists = orgVerifyAttachment.getAttachment();
                    attachmentLists = attachmentLists.replace("[","");
                    attachmentLists = attachmentLists.replace("]","");
                    attachmentLists = attachmentLists.replace("\"","");
                    String[] attachment = attachmentLists.split(",");
                    for (String s:attachment) {
                        orgVerifyAttachment.setOrgVerifyId(orgVerify.getId());
                        orgVerifyAttachment.setType(0);
                        orgVerifyAttachment.setAttachment(s);
                        orgVerifyAttachment.setCreateDate(new Date());
                        orgVerifyAttachmentMapper.insert(orgVerifyAttachment);
                    }
                }else {
                        orgVerifyAttachment.setOrgVerifyId(orgVerify.getId());
                        orgVerifyAttachment.setType(orgVerifyAttachment.getType());
                        orgVerifyAttachment.setAttachment(orgVerifyAttachment.getAttachment());
                        orgVerifyAttachment.setCreateDate(new Date());
                        orgVerifyAttachmentMapper.insert(orgVerifyAttachment);
                }
            }
        } else if (role.equals(1)) {
            //产废端，将危废清单写入表中
            for (OrgVerifyAttachment orgVerifyAttachment : orgVerifyAttachmentList) {
                if (orgVerifyAttachment.getType().equals(0)) {
                    String attachmentLists = orgVerifyAttachment.getAttachment();
                    attachmentLists = attachmentLists.replace("[","");
                    attachmentLists = attachmentLists.replace("]","");
                    attachmentLists = attachmentLists.replace("\"","");
                    String[] attachment = attachmentLists.split(",");
                    for (String s:attachment) {
                        orgVerifyAttachment.setOrgVerifyId(orgVerify.getId());
                        orgVerifyAttachment.setType(0);
                        orgVerifyAttachment.setAttachment(s);
                        orgVerifyAttachment.setCreateDate(new Date());
                        orgVerifyAttachmentMapper.insert(orgVerifyAttachment);
                    }
                }else {
                    orgVerifyAttachment.setOrgVerifyId(orgVerify.getId());
                    orgVerifyAttachment.setType(orgVerifyAttachment.getType());
                    orgVerifyAttachment.setAttachment(orgVerifyAttachment.getAttachment());
                    orgVerifyAttachment.setCreateDate(new Date());
                    orgVerifyAttachmentMapper.insert(orgVerifyAttachment);
                }
            }
            //经营端，将废品类别写入表中
            List<String> list = JSONArray.parseArray(wasteTypeList, String.class);
//            ArrayList<OrgWasteType> list  =
//                    JSON.parseObject(wasteTypeList, new TypeReference<ArrayList<OrgWasteType>>(){});
            for (String i : list) {
                OrgWasteType orgWasteType = new OrgWasteType();
                orgWasteType.setOrgVerifyId(orgVerify.getId());
                orgWasteType.setOrgId(orgVerify.getOrgId());
                orgWasteType.setWasteTypeId(Integer.valueOf(i));
                orgWasteType.setWasteTypeName(wasteTypeMapper.selectById(Integer.valueOf(i)).getName());
                orgWasteType.setCreateDate(new Date());
                orgWasteTypeMapper.insert(orgWasteType);
            }
        }

        return ResponseParams.ok(null);
    }


    public ResponseParams<?> isOrgVerify() {
        Integer memberId = ss.getCurrentUserId();
        OrgVerify isOrgVerify = orgVerifyMapper.isOrgVerify(memberId);
        Map<String, Object> params = new HashMap<>();
        if (isOrgVerify == null) {
            params.put("code", 3);
        } else {
            params.put("code", isOrgVerify.getExamState());
            if (isOrgVerify.getExamState() == 2) {
                params.put("rejectReason", isOrgVerify.getRejectReason());
            }
        }
        return ResponseParams.ok(params);
    }
}
